package com.djl.service.impl;

import com.djl.crowd.entity.Admin;
import com.djl.crowd.entity.AdminExample;
import com.djl.crowd.util.CrowdConstant;
import com.djl.crowd.util.CrowdUtil;
import com.djl.crowd.util.exception.LoginAcctAlReadyInUserException;
import com.djl.crowd.util.exception.LoginAcctAlReadyInUserFroUpdateException;
import com.djl.crowd.util.exception.LoginFailedException;
import com.djl.mapper.AdminMapper;
import com.djl.service.AdminService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
public class AdminServiceImpl implements AdminService {


    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;


    @Override
    public Admin getAdminByLoginAcct(String username) {
        AdminExample example = new AdminExample();
        AdminExample.Criteria criteria = example.createCriteria();
        criteria.andLoginAcctEqualTo(username);
        List<Admin> adminList = adminMapper.selectByExample(example);
        return adminList.get(0);
    }

    @Override
    public void saveAdminRoleRelationship(List<Integer> roleIdList, Integer adminId) {
        // 根据adminId删除旧的关联关系数据
        adminMapper.deleteRelationship(adminId);

        // 根据roleIdList 和adminId保存新的关联关系
        if (roleIdList != null && roleIdList.size() > 0) {
            adminMapper.insertNewRelationship(adminId, roleIdList);
        }
    }

    @Override
    public void update(Admin admin) {
        try {
            adminMapper.updateByPrimaryKeySelective(admin);
        } catch (Exception e) {
            e.printStackTrace();
            if (e instanceof DuplicateKeyException) {
                throw new LoginAcctAlReadyInUserFroUpdateException(CrowdConstant.MESSAGE_LOGIN_ACCT_ALREADY_IN_USE);
            }
        }

    }

    @Override
    public Admin getAdminById(Integer adminId) {
        return adminMapper.selectByPrimaryKey(adminId);
    }

    @Override
    public int remove(Integer adminId) {
        return adminMapper.deleteByPrimaryKey(adminId);
    }

    @Override
    public PageInfo<Admin> getPageByKeyword(String keyword, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Admin> adminList = adminMapper.selectByKeyword(keyword);
        return new PageInfo<>(adminList);
    }

    @Override
    public Admin getAdminByLoginAcct(String loginAcct, String userPswd) {
//        Admin admin = adminMapper.selectByLoginAcct(loginAcct, userPswd);
        AdminExample example = new AdminExample();
        example.createCriteria().andLoginAcctEqualTo(loginAcct);
        List<Admin> adminList = adminMapper.selectByExample(example);

        // 判断集合是否为空，如果为空，没有账户信息，抛出异常
        if (adminList.isEmpty()) {
            throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);
        }

        // 判断集合长度，如果记录大于一，抛出异常，账号需要唯一性
        if (adminList.size() > 1) {
            throw new LoginFailedException(CrowdConstant.MESSAGE_SYSTEM_ERROR_LOGIN_NOT_UNIQUE);
        }

        // 如果 admin为 null抛出异常
        Admin admin = adminList.get(0);
        if (admin == null) {
            throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);
        }

        // 如果不为null,将数据库中的密码从admin对象中取出
        String userPswdDB = admin.getUserPswd();

        // 将密码进行加密
        String userPswdMd5 = CrowdUtil.md5Utils(userPswd);

        // 判断密码是否一致
        if (!Objects.equals(userPswdDB, userPswdMd5)) {
            throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);
        }

        return admin;
    }

    @Override
    public List<Admin> getAll() {
        return adminMapper.selectByExample(null);
    }

    @Override
    public int save(Admin admin) {
        System.out.println(admin + "===" + admin.getUserName());
        // 加密用户输入的密码
        String userPswd = admin.getUserPswd();
//        userPswd = CrowdUtil.md5Utils(userPswd);
        userPswd = bCryptPasswordEncoder.encode(userPswd);
        admin.setUserPswd(userPswd);


        // 生成创建时间
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String createTime = format.format(date);
        admin.setCreateTime(createTime);

        //执行保存
        int num = 0;
        try {
            num = adminMapper.insert(admin);
        } catch (Exception e) {
            e.printStackTrace();
            if (e instanceof DuplicateKeyException) {
                throw new LoginAcctAlReadyInUserException(CrowdConstant.MESSAGE_LOGIN_ACCT_ALREADY_IN_USE);
            }
        }
        return num;
    }
}
